package com.example.component;

import com.example.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author yinxin
 * @version 1.0
 * @Description:
 * @date 2022/6/213:54
 */
@Component
@Slf4j
public class SmsComponent {

    /**
     * 发送地址
     */
    public static final String urlTemplate = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    public void send(String to,String templateId,String value){
        String url = String.format(urlTemplate, to, templateId, value);
        HttpHeaders headers =new HttpHeaders();
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("url={},body={}",url,response.getBody());
        if(response.getStatusCode() == HttpStatus.OK){
            log.info("发送短信验证码成功");
        }else {
            log.info("发送短信验证码失败:{}",response.getBody());
        }
    }
}
